package com.csy.View;
import com.csy.Controller.Controller;
import com.csy.chat.Get_chat_History;
import com.csy.chat.chat_message;
import com.csy.client_server.client_side.ClientSendServer;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.StageStyle;

import java.io.IOException;
import java.net.Socket;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.Vector;

import javafx.scene.control.Button;
import com.csy.client_server.client_side.ClientSendServer;
import com.csy.client_server.client_side.MultiClient;
import com.csy.mysql_util.MysqlUtil;
import javafx.event.Event;


public class MainWindow extends window {
    private TextArea friendList;
    private TextArea chatList;
    private TextField msg;
    private Socket client;
    private String name;
    private ClientSendServer sendServer;
    private ClientReadServer readServer;
    private Thread read;
    private Thread send;

    public MainWindow(StringBuffer name,String Ip)  {
        try {
            root = FXMLLoader.load(getClass().getResource("Fxml/MainWindow.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Scene scene = new Scene(root, 1084, 700);
        scene.setFill(Color.TRANSPARENT);
        setScene(scene);
        initStyle(StageStyle.TRANSPARENT);
        setResizable(false);
        setTitle("Chat Room");
        msg = ((TextField) $("input"));
        friendList = ((TextArea) $("FirendList"));
        chatList = ((TextArea) $("ChatList"));

        setIcon();
        move();
        quit();
        minimiser();

        friendList.setEditable(false);
        chatList.setEditable(false);
        friendList.setWrapText(true);
        chatList.setWrapText(true);

        Get_chat_History temp=new Get_chat_History();
        for(int i=0;i<temp.getLength();i++)
        {
            chatList.appendText(new String(temp.getTime(i))+"\n");
            chatList.appendText(new String(temp.getName(i))+":"+new String(temp.getTalk(i))+"\n");
        }


        try
        {
            client=new Socket(Ip,6666);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        this.name=new String(name);




        sendServer=new ClientSendServer(client,name);
        readServer=new ClientReadServer(client);

        //创建读取服务器端信息的线程和发送服务器端信息的线程
        read=new Thread(readServer);
        send=new Thread(sendServer);

        //启动线程
        read.start();
        send.start();


        msg.setOnKeyPressed(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent event) {
                if(event.getCode() == KeyCode.ENTER){
                    if(msg.getText().equals("\n"))
                    {
                        msg.setText("");
                    }
                    else
                    {
                        send.interrupt();
                        Thread send2 = new Thread(sendServer);
                        send2.start();
                        String tempTXT = "G:" + msg.getText();
                        tempTXT=tempTXT.replace('\n',' ');
                        sendServer.read(new StringBuffer(tempTXT));
                        msg.setText("");
                        send2.interrupt();
                    }
                }
            }
        });



        ((Button) $("send")).setOnAction(event -> {
            if(msg.getText().equals("\n"))
            {
                msg.setText("");
            }
            else
            {
                send.interrupt();
                Thread send2 = new Thread(sendServer);
                send2.start();
                String tempTXT = "G:" + msg.getText();
                tempTXT=tempTXT.replace('\n',' ');
                sendServer.read(new StringBuffer(tempTXT));
                msg.setText("");
                send2.interrupt();
            }
        });
    }


    @Override
    public void quit() {
        ((Button) $("quit1")).setTooltip(new Tooltip("退出"));
        ((Button) $("quit1")).setOnAction(event -> {
            Thread send2=new Thread(sendServer);
            send2.start();
            sendServer.read(new StringBuffer("exit"));
            System.out.println("窗口已关闭!");
            close();
            System.exit(0);
        });
    }

    @Override
    public void minimiser() {
        ((Button) $("minimiser1")).setTooltip(new Tooltip("最小化"));
        ((Button) $("minimiser1")).setOnAction(event -> {
            setIconified(true);
        });
    }

    class ClientReadServer implements Runnable
    {
        private Socket socket;
        private chat_message temp;
        public ClientReadServer(Socket socket)
        {
            this.socket=socket;
        }
        @Override
        public synchronized void run()
        {
            //获取服务器端输入流
            try
            {
                Scanner scanner=new Scanner(socket.getInputStream());
                boolean flag=false;
                while(scanner.hasNext())
                {
                    String mag=scanner.next();
                    if(mag.startsWith("~`"))
                    {
                        flag=false;
                        continue;
                    }
                    if(mag.startsWith("`"))
                    {
                        if(!flag)
                        {
                            friendList.setText("");
                            flag=true;
                        }
                        mag=mag.replace('`',' ');
                        System.out.println(mag);
                        friendList.appendText(mag);
                        friendList.appendText("\n");
                        continue;
                    }
                    else if(mag.startsWith("~"))
                    {
                        if(!flag)
                        {
                            friendList.setText("");
                            flag=true;
                        }
                        mag=mag.replace('~',' ');
                        System.out.println(mag);
                        friendList.appendText(mag);
                        friendList.appendText("\n");
//                            jta.paintImmediately(jta.getBounds());
                        continue;
                    }
                    else
                    {
                        String mag2 = scanner.next();
                        String mag3 = scanner.next();
                        String mag4 = scanner.next();
                        chatList.appendText(mag + " " + mag2);
                        chatList.appendText("\n");
//                            jta2.paintImmediately(jta2.getBounds());
                        chatList.appendText(mag3 + ":" + mag4);
                        chatList.appendText("\n");
//                            chatList.scrollTop = textarea.scrollHeight;
//                            chatList.paintImmediately(jta2.getBounds());
                    }

                }
                scanner.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}